<template>
  <div>
    <tablePaging :tableItem="tableItem" :operationItem="operationItem"></tablePaging>
    <el-dialog v-model="data.dialogVisible" :title="data.title" @close="closeHandle">
      <el-form v-if="data.code == 'commonCode'" ref="formRef" :model="customer" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="图片名称" prop="customerName">
              <el-input v-model="customer.customerName" placeholder="输入客服名称" style="width: 240px"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="10">
            <el-form-item label="上传图片" prop="customerImg">
              <ImgUpload v-model="customer.customerImg"></ImgUpload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-form :rules="rules" ref="formRef" :model="form" label-width="120px" v-if="data.code == 'kfConfigCode'">
        <el-row>
          <el-col :span="10">
            <el-form-item label="课程类型" prop="courseType">
              <el-select clearable v-model="form.courseType" placeholder="请选择课程类型" @change="selectCourseHandle">
                <el-option v-for="item in data.courseList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="客服" prop="userid">
              <el-select clearable v-model="form.userid" placeholder="请选择客服" @change="selectServerHandle">
                <el-option v-for="item in data.serverList" :key="item.userid" :label="item.name" :value="item.userid" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="状态" prop="disableFlag">
              <el-radio v-model="form.disableFlag" :label="0">启用</el-radio>
              <el-radio v-model="form.disableFlag" :label="1">禁用</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-form :rules="rules" ref="formRef" :model="form" label-width="120px" v-if="routeQuery.code == 'courseConfigCode'">
        <el-row>
          <el-col :span="10">
            <el-form-item label="课程类型" prop="courseType">
              <el-select clearable v-model="form.courseType" placeholder="请选择课程类型">
                <el-option v-for="item in data.courseList" :key="item" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="所属地区">
              <el-select clearable v-model="form.provinceIdList" placeholder="请选择地区" multiple :collapse-tags="true" :collapse-tags-tooltip="true">
                <el-option :key="'select-all'" :label="'全选'" :value="null" @click.stop="toggleSelectAll"/>
                <el-option v-for="item in data.areaList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="开考日期" prop="examStartDate">
              <el-date-picker
                  v-model="form.examStartDate"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="请选择开考日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="加群截止日期" prop="addGroupEndDate">
              <el-date-picker
                  v-model="form.addGroupEndDate"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="请选择截止日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="状态" prop="disableFlag">
              <el-radio v-model="form.disableFlag" :label="0">启用</el-radio>
              <el-radio v-model="form.disableFlag" :label="1">禁用</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="data.dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="confirm()"> 确 定</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import tablePaging from '@/views/common/component/table-paging'
import {onMounted, reactive, ref,} from 'vue'
import {operationItem, tableItem} from './const.js'
import {addBaseConfig, delBaseConfig, disableBaseConfig, editBaseConfig} from '@/api/config/param'
import {ElMessage} from 'element-plus'
import {useRoute, useRouter} from 'vue-router'
import {listDictItemByCode} from '@/api/config/dic'
import {listWecomUser} from '@/api/common'
import ImgUpload from "@/views/common/component/upload/img-upload.vue";

const router = useRouter()
const route = useRoute()
const routeQuery = reactive(route.query)
const { proxy } = getCurrentInstance();
const isAdd = ref(false)
onMounted(() => {
  let request = tableItem.pageInfo.request
  request.parentId = routeQuery.id
  data.title = routeQuery.name
  data.code = routeQuery.code
  data.id = routeQuery.id
  initData()
  initTableItem()
})
const data = reactive({
  code: '',
  courseType: '',
  value: '',
  extra: '',
  dialogVisible: false,
  title: '',
  typeCode: '',
  courseList: [],
  serverList: [],
  areaList: []
})
const form = reactive({
  id: '',
  parentId: '',
  courseType: '',
  userid: '',
  extra: '',
  disableFlag: 0,
  examStartDate: '',
  addGroupEndDate: '',
  value: '',
  serverName: '',
  courseName: '',
  provinceIdList: []
})
const customer = reactive({
  customerImg: '',
  customerName: ''
})
const formRef = ref('')
const rules = reactive({
  disableFlag: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  courseType: [{ required: true, message: '请选择课程类型', trigger: 'blur' }],
  examStartDate: [{ required: true, message: '请选择开考日期', trigger: 'blur' }],
  addGroupEndDate: [{ required: true, message: '请选择加群截止日期', trigger: 'blur' }],
  extra: [{ required: true, message: '请选择', trigger: 'blur' }],
  customerName: [{required: true, message: '请输入图片名称', trigger: 'blur'}]
})
const toggleSelectAll = () => {
  if (form.provinceIdList.length-1 === data.areaList.length) {
    form.provinceIdList = [];
  } else {
    form.provinceIdList = data.areaList.map(option => option.id);
  }
};

const initData = () => {
  listDictItemByCode({typeCode: 'courseTypeCode'}).then(res => {
    data.courseList = res.rows
  })
  listDictItemByCode({typeCode: 'regionCode'}).then(res => {
    data.areaList = res.rows
  })
  listWecomUser().then(res => {
    data.serverList = res.rows
  })
}
function closeHandle() {
  formRef.value.resetFields()
  data.dialogVisible = false

}
function selectCourseHandle(e) {
  let selectedCourseItem = data.courseList.find(item => item.id == e)
  form.courseName = selectedCourseItem.name
}
function selectServerHandle(e) {
  let selectedServerItem = data.serverList.find(item => item.userid == e)
  form.serverName = selectedServerItem.name
}

const confirm = () => {
  console.log(customer)
  if (!formRef.value) return
  formRef.value.validate((valid, fields) => {
    if(!valid){return}
    const { courseType, disableFlag, provinceIdList} = form
    let dataForm = { courseType, disableFlag, provinceIdList }
    dataForm.id = isAdd.value? '' : form.id
    dataForm.parentId = data.id
    dataForm.code = data.code
    if(data.code == 'kfConfigCode') {
      dataForm.extra = form.userid
      let newArray = [{
        desc: '客服名称',
        content: form.serverName,
        key: 'name'
      },
        {
          desc: '客服code',
          content: form.userid,
          key: 'code'
        },
      ]
      dataForm.value = JSON.stringify(newArray)
    } else if(data.code == 'courseConfigCode') {
      let newArray = [{
        desc: '开考日期',
        content: form.examStartDate,
        key: 'examStartDate'
      },
        {
          desc: '加群截止日期',
          content: form.addGroupEndDate,
          key: 'addGroupEndDate'
        },
      ]
      dataForm.value = JSON.stringify(newArray)
    } else if (data.code == 'commonCode') {
      let newArray = [{
        desc: '图片名称',
        content: customer.customerName,
        key: 'customerName'
      },
        {
          desc: '图片',
          content: customer.customerImg,
          key: 'customerImg'
        },
      ]
      dataForm.value = JSON.stringify(newArray)
    }
    if(isAdd.value) {
      addBaseConfig(dataForm).then(res => {
        ElMessage.success('操作成功'); data.dialogVisible = false; tableItem.pageInfo.paging()
      })
    } else {
      editBaseConfig(dataForm).then(res => {
        ElMessage.success('操作成功'); data.dialogVisible = false; tableItem.pageInfo.paging()
      })
    }
  })
}

function addHandle() {
  isAdd.value = true
  data.dialogVisible = true
  form.courseType = ''
  form.disableFlag = 0
  form.userid = ''
  form.serverName = ''
  form.examStartDate = ''
  form.addGroupEndDate = ''
  form.provinceIdList = []
}
function editHandle(row) {
  console.log(row,'row')
  isAdd.value = false
  data.dialogVisible = true
  form.id = row.id
  form.parentId = row.parentId
  form.courseType = row.courseType
  form.disableFlag = row.disableFlag
  if(routeQuery.code == 'kfConfigCode') {
    form.userid = row.extra
    let selectedServerItem = data.serverList.find(item => item.userid == row.userid)
    form.serverName = selectedServerItem.name
  } else if(routeQuery.code == 'courseConfigCode') {
    form.provinceIdList = []
    if(row.provinceMap) {
      row.provinceMap.map(item => {
        form.provinceIdList.push(item.id)
      })
    }
    let valueArray = JSON.parse(row.value)
    valueArray.map(item => {
      if (item.key == 'examStartDate') {
        form.examStartDate = item.content
      } else if (item.key == 'addGroupEndDate') {
        form.addGroupEndDate = item.content
      }
    })
  } else if (routeQuery.code == 'commonCode') {
    let valueArray = JSON.parse(row.value)
    valueArray.forEach(item => {
      if (item.key == 'customerImg') {
        customer.customerImg = item.content
      } else if (item.key == 'customerName') {
        customer.customerName = item.content
      }
    })
  }
}
function disableHandle(row, disableFlag) {
  disableBaseConfig({id: row.id, disableFlag: disableFlag}).then(res => {
    ElMessage.success('操作成功'); tableItem.pageInfo.paging()
  })
}
function delHandle(row) {
  proxy.$modal.confirm("确定删除" + row.courseTypeName || '').then(() => {
    delBaseConfig(row.id).then(res => {
      ElMessage.success('操作成功'); tableItem.pageInfo.paging()
    })
  })
}
function initTableItem() {
  let menuArray = operationItem.menuArray
  let addMenu = menuArray.find(item => item.code === 'add')
  addMenu.handle = addHandle
  let btnArray = tableItem.btnArray
  let editBtn = btnArray.find(item => item.code == 'edit')
  editBtn.handle = editHandle
  let disableBtn = btnArray.find(item => item.code == 'disable')
  disableBtn.handle = (row) => disableHandle(row, 1)
  let ableBtn = btnArray.find(item => item.code == 'able')
  ableBtn.handle = (row) => disableHandle(row, 0)
  let delBtn = btnArray.find(item => item.code == 'del')
  delBtn.handle = delHandle
}
</script>

<style scoped>
:deep(.el-input__wrapper) {
  width: 200px;
}
</style>
